import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

type UserInfo = {
  species: {
    name: string;
    url: string
  }
};

const fetchById = (userId: number) => new Promise<UserInfo>(resolve => {
  setTimeout(() => {
    resolve({
      species: {
        name: "bulbasaur",
        url: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/1.png"
      },
    });
  }, 500);
});

// MARK: 9、使用 createAsyncThunk 进行异步操作
export const fetchUserById = createAsyncThunk<UserInfo, number>(
  'users/fetchByIdStatus',
  async (userId, thunkApi) => {
    console.log('thunkApi ---> ', thunkApi.dispatch);
    const response = await fetchById(userId);
    return response;
  }
);

const initialState: UserInfo = {
  species: {
    name: '',
    url: ''
  }
};

const usersSlice = createSlice({
  name: 'users',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(fetchUserById.fulfilled, (state, action) => {
      state.species = action.payload.species;
    })
  }
});

export default usersSlice.reducer;
